import React, {useEffect, useRef, useState} from "react";
import {Table, Button, Modal, Switch} from "antd";
import axios from "axios";
import {DeleteOutlined, ExclamationCircleOutlined, SearchOutlined} from "@ant-design/icons";
import UserForm from "../../../components/user-manage/UserForm";

const {confirm} = Modal
export default function RightList() {
    // Table属性
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            render: (region) => {
                return (<b>{region}</b>)
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            key: 'title',
            render: (role) => {
                return role.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'title',
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => {
                return (
                    <Switch checked={roleState} disabled={item.default} onChange={() => handleChange(item)}/>
                )
            }
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <div>
                        <Button type={"primary"} shape="circle" icon={<SearchOutlined/>} disabled={item.default}
                                onClick={() => handleUpdate(item)}/>
                        <Button type={"danger"} shape="circle" style={{margin: 10}} icon={<DeleteOutlined/>}
                                onClick={() => confirmMethod(item)} disabled={item.default}/>
                    </div>
                )
            }
        }
    ]

    // dataSource
    const [dataSource, setDataSource] = useState([])
    const [isModalVisible, setIsModalVisible] = useState(false)
    // 角色权限列表
    const [roleList, setRoleList] = useState([])
    // 区域数组
    const [regionList, setRegionList] = useState([])
    const addForm = useRef(null)
    const updateForm = useRef(null)
    const [isUpdateVisible, setIsUpdateVisible] = useState(false)
    const [isUpdateDisabled, setIsUpdateDisabled] = useState(false)
    const [current, setCurrent] = useState(null)

    // const {roleId,region} = JSON.parse(localStorage.getItem("token"))
    // 获取dataSource
    useEffect(async () => {
        let res = await axios.get('http://localhost:5000/users?_expand=role')
        setDataSource(res.data)
    }, [])
    // 获取区域数组
    useEffect(async () => {
        let res = await axios.get('http://localhost:5000/regions')
        setRegionList(res.data)
    }, [])
    // 获取角色权限列表
    useEffect(async () => {
        let res = await axios.get('http://localhost:5000/roles')
        setRoleList(res.data)
    }, [])

    //确定是否删除弹框
    const confirmMethod = (item) => {
        confirm({
            title: '确定要删除吗',
            icon: <ExclamationCircleOutlined/>,
            // content: 'Some descriptions',
            async onOk() {
                // console.log('OK');
                await deleteMethod(item)
            },
            onCancel() {
                // console.log('Cancel');
            },
        });
    }

    // 删除函数
    const deleteMethod = async (item) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        await axios.delete(`http://localhost:5000/users/${item.id}`)
    }

    // 开关方法
    const onCreate = () => {
        console.log('handleCancel')
        setIsModalVisible(false)
    }
    const onCancel = () => {
        console.log('onCancel')
        setIsModalVisible(false)
    }
    const addFormOk = () => {
        addForm.current.validateFields().then(async res => {
            // console.log(res)
            setIsModalVisible(false)
            let result = await axios.post(`http://localhost:5000/users`, {
                ...res,
                "roleState": true,
                "default": false
            })
            setDataSource([...dataSource], result.data)
            addForm.current.resetFields()
            // console.log(result.data)
        }).catch(err => {
            console.log(err)
        })
    }
    const handleChange = (item) => {
        item.roleState = !item.roleState
        setDataSource([...dataSource])
        axios.patch(`http://localhost:5000/users/${item.id}`, {
            roleState: item.roleState
        })
    }
    const handleUpdate = (item) => {
        console.log(item)
        // 修改状态并不是同步的,需要放在异步函数中完成
        setTimeout(() => {
            setIsUpdateVisible(true)
            if (item.roleId === '1') {
                // 禁用
                setIsUpdateDisabled(true)
            } else {
                // 不禁用
                setIsUpdateDisabled(false)
            }
            updateForm.current.setFieldsValue(item)
        }, 0)
        setCurrent(item)
    }
    const onUpdateCancel = () => {
        setIsUpdateVisible(false)
    }
    const updateOk = () => {
        updateForm.current.validateFields().then(value => {
            setIsUpdateVisible(false)
            setDataSource(dataSource.map(item=>{
                if(item.id===current.id){
                    return{
                        ...item,
                        ...value,
                        role:roleList.filter(data=>data.id===value.roleId)[0]
                    }
                }
                return item
            }))
            setIsUpdateDisabled(!isUpdateDisabled)
            axios.patch(`http://localhost:5000/users/${current.id}`,value)
        })
    }
    return (
        <div>
            <Button type={"primary"} style={{marginBottom: 10}} onClick={() => {
                setIsModalVisible(true)
            }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 5
            }} rowKey={item => item.id}/>
            <Modal
                visible={isModalVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={onCancel}
                onOk={() => addFormOk()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}/>
            </Modal>
            <Modal
                visible={isUpdateVisible}
                title={"更新用户"}
                okText="确定"
                cancelText="取消"
                onCancel={onUpdateCancel}
                onOk={() => updateOk()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={updateForm}
                          isUpdateDisabled={isUpdateDisabled}/>
            </Modal>
        </div>
    )
}
